<template>
  <div class="dashboard-container">
    <div ref="code" class="code">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="20" class="pt15 px5" style="height: 100%">
          <el-col :span="8">
            <el-form-item label="平台" prop="platform">
              <el-select v-model="form.platform" placeholder="请选择平台" disabled clearable>
                <el-option label="小红书" value="xhs">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录方式" prop="loginType">
              <el-select v-model="form.loginType" placeholder="请选择登录方式" clearable>
                <el-option label="二维码" value="qrcode"></el-option>
                <el-option label="Cookie" value="cookie"></el-option>
                <!-- <el-option label="手机号" value="phone"></el-option> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="爬取类型" prop="crawlerType">
              <el-select v-model="form.crawlerType" placeholder="请选择爬取类型" clearable>
                <el-option label="关键词搜索" value="search"></el-option>
                <el-option label="帖子" value="detail"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.loginType === 'cookie'">
            <el-form-item label="登录Cookie">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入登录Cookie"
                v-model="form.cookies">
              </el-input>
            </el-form-item>
          </el-col>
          <div v-if="form.crawlerType === 'search'">
            <el-col :span="8">
              <el-form-item label="爬取开始页数">
                <el-input-number v-model="form.startPage" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="爬取排序">
                <el-select v-model="form.crawlerSortType" placeholder="请选择爬取类型" clearable>
                  <el-option label="全部" value="general"></el-option>
                  <el-option label="最热" value="popularity_descending"></el-option>
                  <el-option label="最新" value="time_descending"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="爬取帖子的数量">
                <el-input-number v-model="form.crawlerMaxNotesCount" :min="1"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="爬取关键词">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="请输入搜索关键词用，分割"
                  v-model="form.keywords">
                </el-input>
              </el-form-item>
            </el-col>
          </div>
          <el-col :span="24" v-if="form.crawlerType === 'detail'">
            <el-form-item label="爬取帖子ID">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="请输入帖子ID用，分割"
                v-model="form.xhsSpecifiedIds">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="爬取评论筛选词">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" placeholder="请输入搜索关键词用，分割"
                v-model="form.filterKeywords">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div ref="divide" class="divide" />
    <div class="log-container">
      <!-- <div class="title">Logcat</div> -->
      <div class="tool-bar">
        <!-- <el-select
        v-model="logLevel"
        size="mini"
        placeholder="日志级别"
        style="width: 100px; margin-left: 10px;"
      >
        <el-option label="Verbose" value="" />
        <el-option label="Debug" value="D" />
        <el-option label="Info" value="I" />
        <el-option label="Warn" value="W" />
        <el-option label="Error" value="E" />
      </el-select> -->
        <el-input v-model="findStr" placeholder="请输入内容" size="mini" prefix-icon="el-icon-search"
          style="width: 150px; margin-left: 10px;" />
        <div class="actions">
          <el-button plain round size="mini" @click="stopCrawler">Stop Crawler</el-button>
          <el-button class="right mr10" icon="el-icon-caret-right" plain circle size="mini" @click="runCrawler" />
          <slot />
          <el-button class="right mr10" icon="el-icon-circle-close" plain circle size="mini" @click="clearConsole" />
        </div>
      </div>
      <div ref="logScroller" v-auto-height:maxHeight="-10" class="log-scroller"
        :style="{ 'max-height': maxHeight + 'px' }">
        <div v-for="(item, index) in showLogs" :key="index">{{ item }}</div>
      </div>
    </div>

    <el-dialog :visible="QrVisible" @close="QrVisible = false">
      <div style="display: flex;align-items: center;justify-content: center;">
        <el-image v-if="QrImage" :src="QrImage" fit="cover" alt="Qr Image"></el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import WebSocketManager from "@/WebSocketClientManager";
export default {
  name: "Dashboard",
  components: {
  },
  data() {
    return {
      maxHeight: 500,
      QrImage: '',
      QrVisible: false,
      form: {
        platform: 'xhs',
        loginType: 'qrcode',
        cookies: '',
        crawlerType: 'detail',
        crawlerSortType: 'general',
        startPage: 1,
        crawlerMaxNotesCount: 10000,
        keywords: "补习（班）,线上辅导,衔接班",
        filterKeywords: "求/蹲（语数外等科目）老师,怎么找老师,课时费,怎么学,哪里学,怎么选,有什么推荐,怎么报名,怎么补,（语数外等科目）怎么补,求,分享,求分享,求电子版,拍下,请问,怎么写作,需要,999,111,怎么听,有偿,想听,问价,跟学,购买",
        xhsSpecifiedIds: "662013e00000000001006d7d,666d7ae5000000000e03261d"
      },
      rules: {
        platform: [
          { required: true, message: '请选择平台', trigger: 'blur' },
        ],
        loginType: [
          { required: true, message: '请选择登录方式', trigger: 'change' }
        ],
        crawlerType: [
          { required: true, message: '请选择爬取类型', trigger: 'change' }
        ]
      },
      logLevel: "",
      findStr: '',
      logs: [],
    };
  },
  computed: {
    showLogs() {
      let result = this.logs;
      if (this.findStr) {
        result = result.filter((log) => {
          return log.indexOf(this.findStr) > -1;
        });
      }
      if (this.logLevel) {
        result = result.filter((log) => {
          return log.indexOf(`/${this.logLevel}:`) > 0;
        });
      }
      return result;
    }
  },
  created() {
    this.messageListener = message => {
      if (message.type === "crawler_output") {
        this.logs.push(message.data);
        this.$refs.logScroller.scrollTop = this.$refs.logScroller.scrollHeight;
        if (this.QrImage == '' || this.QrImage == null) {
          this.extractBase64Image(message.data)
        }
        if(this.QrVisible && message.data.includes('Login successful then wait for 5 seconds redirect ...')){
          this.QrVisible = false
          this.$message({
                message: "登录成功然后等待5秒重定向…！",
                type: "success"
              });
        }
      }
    };
    WebSocketManager.getInstance().addMessageListener(this.messageListener);
  },
  mounted() {
    this.dragDivide();
  },
  methods: {
    extractBase64Image(log) {
      // 匹配 [XiaoHongShuLogin.QR_Code_Image] 和后面的 base64 图片数据
      // 定义要搜索的关键词
      const keyword = '[XiaoHongShuLogin.QR_Code_Image]';
      // 检查关键词是否存在于日志中
      if (log.includes(keyword)) {
        // 提取 base64 图片数据
        const base64Start = log.indexOf('data:image/png;base64,');

        if (base64Start !== -1) {
          const base64Data = log.slice(base64Start);
          if (base64Data) {
            console.log("Base64 Image Data:", base64Data);
            this.QrImage = base64Data;
            this.QrVisible = true; // Show the dialog
          } else {
            console.log("No Base64 Image Data Found");
          }
          return base64Data;
        }
      }
    },
    clearConsole() {
      this.logs = [];
    },
    runCrawler() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.QrImage = ''
          request
            .post("/xhsUser/run_crawler", this.form)
            .then(res => {
              this.$message({
                message: "操作成功！",
                type: "success"
              });
            })
            .finally(() => { });
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    stopCrawler() {
      request
        .post("/xhsUser/stop_crawler")
        .then(res => {
          this.$message({
            message: "操作成功！",
            type: "success"
          });
        })
        .finally(() => { });
    },
    dragDivide() {
      const codeMirrorWrapEle = this.$refs.code;
      const divideRef = this.$refs.divide;
      // var mouseDownX;
      var mouseDownY;
      // var initX;
      var initY;
      var doc_onmousemove;
      var doc_onmouseup;
      var flag = false;
      var isMoving = false;

      divideRef.onmousedown = function (e) {
        var obj = divideRef; // 移动目标元素
        // 表示鼠标已按下
        flag = true;

        // 鼠标按下时的鼠标所在的X，Y坐标
        // mouseDownX = e.clientX;
        mouseDownY = e.clientY;

        // 初始位置的X，Y 坐标
        // initX = obj.offsetLeft;
        initY = obj.offsetTop;

        // 保存原来绑定在document的事件
        doc_onmousemove = document.onmousemove;
        doc_onmouseup = document.onmouseup;

        document.onmousemove = move;
        document.onmouseup = obj.onMouseOut = stop;

        function move(e) {
          if (flag && !isMoving) {
            // obj.style.left =
            //   parseInt(e.clientX) - parseInt(mouseDownX) + parseInt(initX) + "px";
            codeMirrorWrapEle.style.height =
              parseInt(e.clientY) -
              parseInt(mouseDownY) +
              parseInt(initY) +
              "px";

            console.log(codeMirrorWrapEle.style.height);

            window.dispatchEvent(new Event("resize"));
            isMoving = true;
            setTimeout(function () {
              isMoving = false;
            }, 10);
          }
          return false;
        }
        function stop() {
          flag = false;
          document.onmousemove = doc_onmousemove; // 原来的事件回复绑定
          document.onmouseup = doc_onmouseup;
        }
        return false; // 可以防止在拖动的时候选中文本
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 0px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.checkbox-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.checkbox-header {
  line-height: 30px;
  background: #f5f7fa;
  margin: 0;
  padding: 5px 0 5px 15px;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
  color: #000;
  flex-wrap: wrap;
}

.checkbox-group {
  padding: 5px 15px 15px 15px;
  height: 100%;
  overflow: auto;
  flex-grow: 1;
}

.checkbox-item {
  margin-top: 10px;
  display: block;
}

.code {
  height: 350px;
  overflow: auto;
  overflow-x: hidden;
}

.divide {
  font-size: 13px;
  padding: 6px 0 6px 10px;
  background: #fff;
  color: #303133;
  cursor: ns-resize;
  -moz-user-select: none;
  /*火狐*/
  -webkit-user-select: none;
  /*webkit浏览器*/
  -ms-user-select: none;
  /*IE10*/
  -khtml-user-select: none;
  /*早期浏览器*/
  user-select: none;
}

.log-container {
  color: #303030;
}

.title {
  background-color: #eeeeee;
  border: 1px solid #5555553b;
  padding: 5px 10px;
}

.tool-bar {
  background-color: #f2f2f2;
  display: flex;
  padding: 10px;
}

.tool-bar .actions {
  flex-grow: 1;
  margin-left: 25px;
  padding-right: 5px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.log-scroller {
  overflow: auto;
  padding: 5px 5px 1.5em 10px;
}
</style>